import React, { useEffect, useState } from 'react'
import AppDialog from '../../components/AppDialog'
import { Form, Input, Button, Space } from 'antd';
import Message from '../../components/Message';
import { addRoles, editRoles } from "../../api/roles";

const { TextArea } = Input;

const AddOrEditRole = ({ visible, roleInfo, onHide }) => {
  const tailLayout = {
    wrapperCol: {
      offset: 10,
      span: 14,
    },
  };
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (visible && roleInfo.id) {
      const initialValues = {
        roleName: roleInfo.roleName,
        roleDesc: roleInfo.roleDesc
      }
      form.setFieldsValue(initialValues)
    }
  }, [roleInfo])

  // 点击确定
  const onFinish = async (values) => {
    setLoading(true)
    if (!roleInfo.id) {
      await addRoles(values).finally(() => {
        setLoading(false)
      })
      Message("success", "添加用户成功");
    } else {
      values.id = roleInfo.id
      await editRoles(values).finally(() => {
        setLoading(false)
      })
      Message("success", "编辑用户成功");
    }

    handleDialogClosed('success')
  };

  // 提交表单且数据验证失败后回调事件
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    form.resetFields();
    onHide(type)
  };

  return (visible ?
    <AppDialog
      title={roleInfo.id ? '编辑角色' : '添加角色'}
      visible={visible}
      onClosed={handleDialogClosed}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="角色名称"
          name="roleName"
          rules={[{ required: true, message: '请输入角色名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="角色描述"
          name="roleDesc"
          rules={[{ required: true, message: '请输入角色描述' }]}
        >
          <TextArea rows={2} />
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>确定</Button>
            <Button onClick={() => handleDialogClosed()}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </AppDialog>
    : null
  )
}

export default AddOrEditRole
